package cn.krund.lyc.hotlerobot.Ros.service.communication;

import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import cn.krund.lyc.hotlerobot.Ros.common.entity.ByteCache;
import cn.krund.lyc.hotlerobot.utils.KrundLog;

/**
 * @包名: cn.krund.lyc.hotlerobot.robot.service.communication
 * @作者: 刘育成
 * @时间: 2018/4/5  14:18
 * @org: 克路德人工智能
 * @描述: TODO
 * @fileName: ClientSocketRunnable
 */

public class ClientSocketRunnable extends CommunicationRunnable {

    private static final int CACHE_MAX_SIZE = 1024 * 1024;        // 缓存的最大尺寸
    private ByteCache m_dataBuffer;                             // 通讯数据缓存


    private int index = 0;


    public ClientSocketRunnable(Socket socket, IRosCommunicationListener communicationListener) {
        super(socket, communicationListener);
        this.m_dataBuffer = new ByteCache(CACHE_MAX_SIZE);     // 实例化数据缓存类
        phoneSockets.add(this.m_socket);                     // 将客户端的socket添加到列表中
    }

    @Override
    protected void socketHandler(Socket socket) throws Exception {
        DataInputStream readStream = new DataInputStream(this.m_socket.getInputStream());    // 获取输入流
        byte[] buf = new byte[1024 * 1024];
        while (socket != null && socket.isConnected()) {
            int readLen = readStream.read(buf);
            if (index > 99) {
                index = 00;
            }
            index++;
            if (readLen > 0) {
                byte[] datas = new byte[readLen];

                System.arraycopy(buf, 0, datas, 0, readLen);                                        // 截取字符串
                // 将从socket输入流中读取到的数据写入dataBuffer中

                this.m_dataBuffer.add(datas);

                this.sendDataToRos(datas);

            } else {
                break;
            }
        }

    }

    /**
     * 发送从客户端传过来的数据到Ros端--
     *
     * @param
     */
    private void sendDataToRos(byte[] datas) {
        if (super.RosSocket != null && super.RosSocket.isConnected()) {
            try {
                KrundLog.i("--数据", "开始向Ros转发数据 data=" + datas);
                DataOutputStream printStream = new DataOutputStream(super.RosSocket.getOutputStream());// 获取输出流
                printStream.write(datas);                                          // 将从客户端获取到的协议数据发送到ros
                printStream.flush();
                Log.i("--数据", "完成向Ros转发的数据");
            } catch (IOException e) {
                e.printStackTrace();

            }
        }
    }
}
